package com.ruoyi.project.erp.saleservices.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.OddUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.project.erp.setupbill.domain.Setupbill;
import com.ruoyi.project.erp.setupbill.service.ISetupbillService;
import com.ruoyi.project.erp.setupbills.domain.Setupbills;
import com.ruoyi.project.erp.setupbills.service.ISetupbillsService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.erp.saleservices.domain.Saleservices;
import com.ruoyi.project.erp.saleservices.service.ISaleservicesService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2020-09-08
 */
@Controller
@RequestMapping("/erp/saleservices")
public class SaleservicesController extends BaseController
{
    private String prefix = "erp/saleservices";

    @Autowired
    private ISaleservicesService saleservicesService;
    @Autowired
    private ISetupbillService setupbillService;
    @Autowired
    private ISetupbillsService setupbillsService;


    @RequiresPermissions("erp:saleservices:view")
    @GetMapping()
    public String saleservices()
    {
        return prefix + "/saleservices";
    }

    @RequiresPermissions("erp:saleservices:view")
    @GetMapping("/saleservicesinfo")
    public String saleservicesinfo()
    {
        return "erp/saleservicesinfo/saleservices";
    }

    /**
     * 手机端新增保存
     */
    @PostMapping("/addOrder")
    @ResponseBody
    public AjaxResult addOrder(@RequestBody JSONObject json)
    {
        List<Saleservices> saleservicesList = json.getJSONArray("saleservicesList").toJavaList(Saleservices.class);
        int num =0;
        String isChangeProduct="否";
        String isChangeDeal="否";
        String flag="0";
            for(int i=0;i<saleservicesList.size();i++){
                Saleservices temp = saleservicesList.get(i);
                if("保修".equals(temp.getCtype())){
                    temp.setSt("已处理");
                }else{
                    temp.setSt("未处理");
                    flag="1";
                    isChangeProduct="是";
                    isChangeDeal="是";
                }
                temp.setSysdt(new Date());
                num += saleservicesService.insertSaleservices(temp);
            }
            //修改售后次数，是否换货，换货是否未处理
           Setupbills setupbills = setupbillsService.selectSetupbillsById(saleservicesList.get(0).getMid());
            if(num>0){
                int oldTimes = Integer.parseInt(setupbills.getServiceTimes());
                int newTimes = saleservicesList.size();
                setupbills.setServiceTimes(String.valueOf(oldTimes+newTimes));
                if("1".equals(flag)){
                    setupbills.setIsChangeDeal(isChangeDeal);
                    setupbills.setIsChangeProduct(isChangeProduct);
                }
                setupbillsService.updateSetupbills(setupbills);
            }
        return toAjax(num);
    }


    /**
     * 审批
     */
    @RequiresPermissions("erp:saleservices:edit")
    @PostMapping("/reviewSaleService")
    @ResponseBody
    public AjaxResult reviewSaleService(Long id)
    {
        //根据id获取售后单信息
        Saleservices temp =new Saleservices();
        temp.setDealemp(getSysUser().getF102());
        temp.setDealdt(new Date());
        temp.setId(id);
        temp.setSt("已处理");
        int num = saleservicesService.updateSaleservices(temp);
        Saleservices saleservices1 = saleservicesService.selectSaleservicesById(id);
        if(num >0){
            //判断当前施工单是否还有未处理售后单
            Setupbills setupbills = setupbillsService.selectSetupbillsById(saleservices1.getMid());
            Saleservices saleservices = new Saleservices();
            saleservices.setMid(saleservices1.getMid());
            List<Saleservices> saleservicesList = saleservicesService.selectSaleservicesList(saleservices);
            int doCount =0;
            for(Saleservices tempin : saleservicesList){
                if("已处理".equals(tempin.getSt())){
                    doCount++;
                }
            }
            //更新处理状态
            if(doCount == saleservicesList.size()){
                setupbills.setIsChangeDeal("否");
                setupbillsService.updateSetupbills(setupbills);
            }
        }
        return toAjax(num);
    }
    /**
     * 撤销审批
     */
    @RequiresPermissions("erp:saleservices:edit")
    @PostMapping("/disReviewSaleService")
    @ResponseBody
    public AjaxResult disReviewSaleService(Long id)
    {
        //根据id获取售后单信息
        Saleservices temp =new Saleservices();
        temp.setId(id);
        Saleservices saleservices = saleservicesService.selectSaleservicesById(id);
        Setupbills setupbills = setupbillsService.selectSetupbillsById(saleservices.getMid());
        int num = saleservicesService.disReviewSaleservices(temp);
        if(num >0){
            setupbills.setIsChangeDeal("是");
            setupbillsService.updateSetupbills(setupbills);
        }
        return toAjax(num);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("erp:saleservices:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Saleservices saleservices)
    {
        //startPage();

        Integer pageNum = ServletUtils.getParameterToInt(Constants.PAGE_NUM);
        System.out.println("[pageNum]+++++++++++++++"+pageNum);
        Integer pageSize =ServletUtils.getParameterToInt(Constants.PAGE_SIZE);
        List<Saleservices> list = saleservicesService.selectSaleservicesList(saleservices);
        List<Saleservices> resultList = new ArrayList<>();
        List<Saleservices> resultQueryList = new ArrayList<>();
        int totalPage = list.size()/pageSize+1;
        int count = pageNum*pageSize;
        if (pageNum == totalPage){
            count = list.size();
        }
        for(int start = (pageNum-1)*pageSize;start<count;start++){
            resultList.add(list.get(start));
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(resultList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


   /* *//**
     * 导出主子列表
     *//*
    @RequiresPermissions("erp:setupbill:export")
    @PostMapping("/exportQuery")
    @ResponseBody
    public AjaxResult exportQuery(long[] rowsId)
    {
        List<Setupbills> resultList = new ArrayList();
        List<Setupbills> list = setupbillsService.querySetupbillsList(rowsId);
        for(int i=0;i<list.size();i++){
            Saleservices saleservices = new Saleservices();
            saleservices.setMid(list.get(i).getId());
            List<Saleservices> saleservicesList = saleservicesService.selectSaleservicesList(saleservices);
            for(int j=0;j<saleservicesList.size();j++){
                Setupbill temp = new Setupbill();
                temp.setId(list.get(i).getId());
                temp.setSetuppic(list.get(i).getSetuppic());
                temp.setSt(list.get(i).getSt());
                temp.setVinpic(list.get(i).getVinpic());
                temp.setVin(list.get(i).getVin());
                temp.setCarstd(list.get(i).getCarstd());
                temp.setCode(list.get(i).getCode());
                temp.setCreditdt(list.get(i).getCreditdt());
                temp.setCreditemp(list.get(i).getCreditemp());
                temp.setCtype(list.get(i).getCtype());
                temp.setDdate(list.get(i).getDdate());
                temp.setEmp(list.get(i).getEmp());
                temp.setShopname(list.get(i).getShopname());
                temp.setMemo(list.get(i).getMemo());
                temp.setMcode(saleservicesList.get(j).getMcode());
                if(saleservicesList.get(j).getSmemo() != null){
                    temp.setSmemo(saleservicesList.get(j).getSmemo());
                }
                temp.setSalectype(saleservicesList.get(j).getCtype());
                resultList.add(temp);
            }
        }
        ExcelUtil<Setupbill> util = new ExcelUtil<Setupbill>(Setupbill.class);
        return util.exportExcel(resultList, "setupbill");
    }*/

    /**
     * 导出主子列表
     */
    @RequiresPermissions("erp:saleservices:export")
    @PostMapping("/exportAll")
    @ResponseBody
    public AjaxResult exportAll(Setupbills setupbills)
    {
        List<Setupbills> resultList = new ArrayList();
        List<Setupbills> list = setupbillsService.selectSetupbillsList(setupbills);
        for(int i=0;i<list.size();i++){
            Saleservices saleservices = new Saleservices();
            saleservices.setMid(list.get(i).getId());
            List<Saleservices> saleservicesList = saleservicesService.selectSaleservicesList(saleservices);
            for(int j=0;j<saleservicesList.size();j++){
                Setupbills temp = new Setupbills();
                temp.setId(list.get(i).getId());
                temp.setSt(list.get(i).getSt());
                temp.setVin(list.get(i).getVin());
                temp.setCarstd(list.get(i).getCarstd());
                temp.setCode(list.get(i).getCode());
                temp.setDdate(list.get(i).getDdate());
                temp.setShopname(list.get(i).getShopname());
                temp.setSmemo(list.get(i).getSmemo());
                temp.setMcode(saleservicesList.get(j).getMcode());
                if(saleservicesList.get(j).getSmemo() != null){
                    temp.setSalememo(saleservicesList.get(j).getSmemo());
                }
                temp.setSalectype(saleservicesList.get(j).getCtype());
                resultList.add(temp);
            }
        }
        ExcelUtil<Setupbills> util = new ExcelUtil<Setupbills>(Setupbills.class);
        return util.exportExcel(resultList, "setupbills");
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("erp:saleservices:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Saleservices saleservices)
    {
        List<Saleservices> list = saleservicesService.selectSaleservicesList(saleservices);
        ExcelUtil<Saleservices> util = new ExcelUtil<Saleservices>(Saleservices.class);
        return util.exportExcel(list, "saleservices");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    //@RequiresPermissions("erp:saleservices:add")
    //@Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody Saleservices saleservices)
    {
        return toAjax(saleservicesService.insertSaleservices(saleservices));
    }

    /**
     * 修改【请填写功能名称】
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Saleservices saleservices = saleservicesService.selectSaleservicesById(id);
        mmap.put("saleservices", saleservices);
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("erp:saleservices:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Saleservices saleservices)
    {
        return toAjax(saleservicesService.updateSaleservices(saleservices));
    }

    /**
     * 删除【请填写功能名称】
     */
    //@RequiresPermissions("erp:saleservices:remove")
    //@Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        Saleservices saleservices = saleservicesService.selectSaleservicesById(Long.parseLong(ids));
        if(!"未处理".equals(saleservices.getSt())){
            return error("订单已处理，不能删除！");
        }
        return toAjax(saleservicesService.deleteSaleservicesByIds(ids));
    }
}
